package com.yvnze.ydyp.config;

import com.yvnze.ydyp.common.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

/**
 * @author HaiPeng Wang
 * @date 2021/8/13 19:44
 * @Description:
 */
@EnableWebMvc //开启SpringMVC注解
@Configuration //配置实现Springmvc的配置文件
public class WebmvcConfig implements WebMvcConfigurer {

    @Autowired
    LoginInterceptor loginInterceptor;


    /**
     * 配置拦截器
     * 参数是一个拦截器注册对象
     * addInterceptor 是注册一个自行编写的拦截器，会组成一个拦截器链
     * addPathPatterns
     * @param registry
     * TODO 拦截路径excludePathPatterns 不生效
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")   //所有路径都被拦截
                .excludePathPatterns(
                        //添加不被拦截的路径
                        "/",
                        "/error",
                        "/swagger-ui.html/**",
                        "/webjars/**",
                        "/swagger-resources/**",
                        "/v2/api-docs",
                        "/csrf",
                        "/favicon.ico"

                );
    }

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/" };

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!registry.hasMappingForPattern("/webjars/**")) {
            registry.addResourceHandler("/webjars/**").addResourceLocations(
                    "classpath:/META-INF/resources/webjars/");
        }
        if (!registry.hasMappingForPattern("/**")) {
            registry.addResourceHandler("/**").addResourceLocations(
                    CLASSPATH_RESOURCE_LOCATIONS);
        }
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").
                allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }

}
